type FetchOpt = Omit<UniNamespace.RequestOptions, "url">;
const HTTP_CODE_MAP: Record<string, string> = {
  404: "请求资源不存在",
  500: "服务器内部错误",
};
class Fetch {
  private instance: Uni["request"];
  private baseUrl: string;
  //   private uniRequestBaseOptions: Partial<UniNamespace.RequestOptions>;

  constructor(opt: { baseUrl: string } & Partial<UniNamespace.RequestOptions>) {
    const { baseUrl, ...rest } = opt;
    // this.uniRequestBaseOptions = rest;
    this.baseUrl = opt.baseUrl;
    this.instance = uni.request;
  }
  res_interceptors(res: GlobalType.RequestType.CompleteRes) {
    const { statusCode, data, errMsg, header } = res;
    if (statusCode === 200) {
      return new Promise((resolve, reject) => {
        resolve(data);
      });
    } else {
      return Promise.reject(`请求失败:${HTTP_CODE_MAP[statusCode]}`);
    }
  }
  req_interceptors(res: GlobalType.RequestType.CompleteRes) {}
  get(url: string, opt: FetchOpt) {
    this.instance({
      method: "GET",
      ...opt,

      url: `${this.baseUrl}${url}`,
      onComplete: (res: GlobalType.RequestType.CompleteRes) => {
        return this.res_interceptors(res);
      },
    });
  }
  async post(url: string, opt: FetchOpt) {
    const res = await this.instance({
      method: "POST",
      ...opt,

      url: `${this.baseUrl}${url}`,
      onComplete: (res: GlobalType.RequestType.CompleteRes) => {
        this.res_interceptors(res);
      },
    });
    return this.res_interceptors(res);
  }
}

export const request = new Fetch({ baseUrl: "http://49.232.169.183" });
